package com.rabbiter.market.common.rabbitmq;

import com.alipay.api.response.AlipayTradeQueryResponse;
import com.rabbiter.market.common.rabbitmq.config.RabbitMqConfig;
import com.rabbiter.market.domain.sale.sale_records.SaleRecords;
import com.rabbiter.market.service.pay.PayService;
import com.rabbiter.market.service.sale_management.sale_records.ISaleRecordsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author: longxianghang
 * @date: 2025/4/16 15:19
 * @description: 死信队列
 */
@Component
public class OrderDlConsumer {

    private static final Logger logger = LoggerFactory.getLogger(OrderDlConsumer.class);

    @Resource
    private ISaleRecordsService saleRecordsService;

    @Resource
    private PayService payService;

    @RabbitListener(queues = RabbitMqConfig.ORDER_DEAD_QUEUE)
    public void orderConsumer(String cn) {
        System.out.println("死信队列获取消息:" + cn);
        if (StringUtils.isEmpty(cn)) {
            return;
        }
        //根据id查询
        SaleRecords query = new SaleRecords();
        query.setCn(cn);
        SaleRecords order = saleRecordsService.getOrderByCn(query);
        if (ObjectUtils.isEmpty(order)) {
            return;
        }
        //获取状态
        //判断未支付 , 关闭订单
        if(order.getPayStatus() != 20){
            try {
                // 防止出现支付宝回调失败的情况
                AlipayTradeQueryResponse response = payService.queryOrder(cn, null, null, null);
                if (!ObjectUtils.isEmpty(response)) {
                    if ("10000".equals(response.getCode())) {
                        order.setPayStatus(20);
                    }
                } else {
                    order.setPayStatus(30);
                    //库存返还
                }
            } catch (Exception e) {
                order.setPayStatus(30);
                logger.info("死信队列更新订单异常：", e);
            }
            saleRecordsService.updateSaleRecords(order);
        }
    }

}
